package generic.gui.util;
  
import javax.swing.text.*;

@SuppressWarnings("serial")
public class FixedLengthDocument extends PlainDocument {
	
	private int maxLength;
	private Character charInicial;
	private Character charFinal; 
	  
    public FixedLengthDocument(int maxLength) {  
        super();  
        char ch1 = 0;
		char ch2 = 1000;
		
		setCharInicial(ch1);
		setCharFinal(ch2);
        this.maxLength = maxLength;  
    }

	public FixedLengthDocument(int maxlen, Character charInicial, Character charFinal) {
		super();
		setCharFinal(charFinal);
		setCharInicial(charInicial);
		this.maxLength = maxlen;
	}
	
	public void insertString(int offset, String str, AttributeSet attr) 
	
            throws BadLocationException {  
		if (getCharInicial() == null)
			setCharInicial(' ');
		
		if (getCharFinal() == null)
			setCharFinal('z');
		
		
			
		if (str == null) return;
		
		if (str.charAt(str.length() -1) >= getCharInicial() && str.charAt(str.length() -1) <= getCharFinal()) {

			if (maxLength <= 0) {   
				super.insertString(offset, str, attr);   
				return;   
			}   

			int ilen = (getLength() + str.length());   
			
			if (ilen <= maxLength)  
				super.insertString(offset, str, attr);
		}
	}

	public Character getCharInicial() {
		return charInicial;
	}

	public void setCharInicial(Character charInicial) {
		this.charInicial = charInicial;
	}

	public Character getCharFinal() {
		return charFinal;
	}

	public void setCharFinal(Character charFinal) {
		this.charFinal = charFinal;
	}
}
